
// 1、正则match方法
var str = 'bcduvbdv w.n vkv';
var reg = new RegExp('w\.n', 'g');
// let reg = /wn/g;
console.log(str.match(reg));

// --------------------------------------------------
// --------------------------------------------------
// -----------author:zhoumingle----------------------
// -------------Promise 专题-------------------------—
// -------------Promise 专题--------------------------
// -------------Promise 专题-------------------------
// -------------Promise 专题-------------------------
// --------------------------------------------------
// --------------------------------------------------


//2、promise
//promise链式调用
// ajax封装
function ajax(url, method) {
    return new Promise(function (resolve, reject) {
        let meth = method || 'get';
        var xhr = new XMLHttpRequest();
        xhr.open(meth, url);
        xhr.send();
        xhr.onload = function (res) {
            if (xhr.readyState === 4) {
                resolve(xhr.responseText);
            }
        };
        xhr.onerror = function (err) {
            reject(err);
        };
    });
};

// 3.promise链式调用
var url1 = 'http://localhost:3000/user?name=wuwang&age=9';
var url2 = 'http://localhost:3000/user?name=zhouxiaole&age=22';
ajax(url1).then(function (res) {
    console.log('name1:', res);
    return ajax(url2);
}).then(function (res) {
    console.log('name2:', res);
})["catch"](function (err) {
    console.log('err', err);
});


// 4.promise.rance做超时函数
function overTimeFn(options, delay=5000) { 
    let Arr = [ajax(options.url), new Promise((resolve, reject) => {
        setTimeout(function () { 
            reject('请求超时。。。');
        }, delay);
    })]
    return Promise.race(Arr);
};

overTimeFn({
    url: 'http://localhost:3000/delay?name=hhhhhh--hhh&age=8998'
})
.then(res => {
    console.log('没有超时', res);
})
.catch(err => {
    console.log(err);
});


// 5.promise的睡眠函数
let sleep = (function async() {
    return function (delay = 1000) { 
        return new Promise((resolve, reject) => {
            setTimeout(()=> resolve(), delay);
        })
    }
})();

setTimeout(async() => { 
    await sleep(7000);
    console.log('测试sleep函数');
 }, 1000)


// 6.promise.all 当所有promis都成功才会成功状态，并行
function promiseAll(arr) {
    arr = arr || [new Promise(resolve => {
        setTimeout(_ => resolve('promiseAll1'), 1000);
    }), new Promise(resolve => {
        setTimeout(_ => resolve('promiseAll2'), 2200);
    }), new Promise((resolve, reject) => {
        setTimeout(_ => resolve('promiseAll3'), 1000);
    })]
    return Promise.all(arr);
 };

 promiseAll().then(res => {
     console.log('success', res);
 }, err => {
     console.log('fail', err);
 });


 // 7.promise队列 简单map 串行
function p1() { 
    return new Promise(resolve => {
         setTimeout(_ => {
             console.log('p1');
             resolve('p1');
        }, 2000);
    })
};

function p2() { 
    return new Promise(resolve => {
        setTimeout(_ => {
            console.log('p2');
            resolve('p2');
        }, 2000);
    })
};

function queue(...arr) {
    let promise = Promise.resolve();
    arr.map(function (item) {
       promise = promise.then(resolve => {
            return item();
       })
    })
 };

//  queue(p1, p2);


 // 8. promise队列 reduce 串行
 function queue2(...arr) {
    arr.reduce(function (pre, next) { 
        return pre.then(resolve => {
            return next();
        })
    }, Promise.resolve());
};

// queue2(p1, p2);


// 9. 自己实现的promise 
class Mypromise {
    static PENDING = 'pending';
    static SUCCESS = 'fullfild';
    static FAILED = 'failed';
    constructor(callback) {
        this.value = null;
        this.status = Mypromise.PENDING;
        this.calback = [];
        try{
            callback(this.resolve.bind(this), this.reject.bind(this));
        } catch (err) {
           this.reject(err);
        }
    };
    resolve(value) {
        if (this.status === Mypromise.PENDING) {
            this.status = Mypromise.SUCCESS;
            this.value = value;
            this.calback[0].onFullfild();
        }
    };
    reject(err) {
        if (this.status === Mypromise.PENDING) {
            this.status = Mypromise.FAILED;
            this.value = err;
            this.calback[1].onFailed();
        }
    };
    then(onFullfild, onFailed) {
        let me = this;
        if (typeof onFullfild != 'function') {
            onFullfild = function () {  };
        };
        if (typeof onFailed != 'function') {
            onFailed = function () {  };
        };
        if (this.status === Mypromise.SUCCESS) {
            onFullfild(me.value);
        };
        if (this.status === Mypromise.FAILED) {
            onFailed(me.value);
        };
        if (this.status === Mypromise.PENDING) {
            this.calback.push({
                onFullfild: function () { 
                    onFullfild(me.value);
                 }
            },
            {
                onFailed: function () { 
                    onFailed(me.value);
                 }
            });

        }
        return this;
    };
    catch(onerrFn) {
        let me = this;
        if (this.status === Mypromise.FAILED) {
            onerrFn(me.value);
        };
        return this;
    }
};

new Mypromise((resolve, reject) => {
    setTimeout(function () { 
        // resolve('mypromise suvccess');
        reject('mypromise fail');
    }, 9000)
}).then(res => {
    console.log(res);
}, err => {
    console.log(err);
}).catch(error => {
    console.log('catch:', error)
})
